#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#include <poll.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>

#define BUFF_SIZE 64
#define NAME_SIZE 20

void* send_msg(void* arg);
void* recv_msg(void* arg);

char name[NAME_SIZE]="[DEAFULT]";
char msg[BUFF_SIZE];

int main(int argc, char const *argv[])
{
	const char* ip = "127.0.0.1";
	char* port = "9876";
	pthread_t send_tid, read_tid;
	void* thread_return;

	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = PF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(ip);
	serv_addr.sin_port = htons(atoi(port));

	int sock = socket(PF_INET, SOCK_STREAM, 0);
	assert(sock>=0);

	// puts("please input name:");
	// fgets(name, NAME_SIZE, stdin);

	sprintf(name, "[%s]", argv[1]);

	if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))<0){
		printf("connect erro\n");
		close(sock);
		return 1;
	}

	pthread_create(&send_tid, NULL, send_msg, (void*)&sock);
	pthread_create(&read_tid, NULL, recv_msg, (void*)&sock);
	pthread_join(send_tid, thread_return);
	pthread_join(read_tid, thread_return);
	close(sock);
	return 0;
}
void* send_msg(void* arg){
	int sock=*((int*)arg);
	char name_msg[NAME_SIZE+BUFF_SIZE];
	while(1){
		//puts("please input (Q to quit):");
		fgets(msg, BUFF_SIZE, stdin);
		if(!strcmp(msg,"Q\n")) 
		{
			close(sock);
			exit(0);
		}
		sprintf(name_msg,"%s %s", name, msg);
		write(sock, name_msg, strlen(name_msg));
	}
	return NULL;
}

void* recv_msg(void* arg){
	int sock = *((int*)arg);
	char name_msg[NAME_SIZE+BUFF_SIZE];
	int str_len=0;
	while(1){ //读完数据
		str_len = recv(sock, name_msg, NAME_SIZE+BUFF_SIZE-1, 0);
		if(str_len<0)
			return (void*)-1; //读完，退出线程
		name_msg[str_len]=0;
		fputs(name_msg, stdout);
	}
	return NULL;
}
